//
//  WJTabBar.m
//  WJBSApp
//
//  Created by dllo on 16/7/14.
//  Copyright © 2016年 王景伟. All rights reserved.
//

#import "WJTabBar.h"
#import "WJ_Publish_VC.h"

@implementation WJTabBar

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        //设置中间添加按钮
        WJBaseButton *publishButton = [WJBaseButton buttonWithType:UIButtonTypeCustom];
        [publishButton setImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
        [publishButton setImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted];
        [publishButton addTarget:self action:@selector(publishButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:publishButton];
        _publishButton = publishButton;
    }
    return self;
}
//重新布局TabBar
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    //    //标记按钮是否已经添加过监听器
    static BOOL added = NO;
    
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    
    // 设置发布按钮的frame
    _publishButton.frame = CGRectMake(0, 0, width, height);
    _publishButton.center = CGPointMake(width * 0.5, height * 0.5 + 2);
    //
    
    // 设置其他UITabBarButton的frame
    CGFloat buttonW = width / 5;
    NSInteger index = 0;
    
    //因为在这里里面需要设置button的监听 如果是view *button 那么就不会提示addtag这个方法
    for (UIControl *button in self.subviews) {
        if (![button isKindOfClass:[UIControl class]] || button == self.publishButton) continue;
        
        // 计算按钮的x值
        CGFloat buttonX = buttonW * ((index > 1)?(index + 1):index);
        button.frame = CGRectMake(buttonX, 0, width / 5, height);
        
        // 增加索引
        index++;
        
        if (added == NO) {
            [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
        }
        
    }
    added = YES;
}

- (void)buttonClick{
    
    //发出一个通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SYTabBarDidSelectNotification" object:nil userInfo:nil];
}
//点击中间按钮事件处理
- (void)publishButtonClick
{
    WJ_Publish_VC *publish = [[WJ_Publish_VC alloc]init];
    [self.window.rootViewController presentViewController:publish animated:YES completion:nil];
}








@end
